package com.chuantou.yuba.ui;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.OtherUserDataTO;
import com.chuantou.yuba.api.to.OtherUserTO;
import com.chuantou.yuba.api.to.TrendsDataTO;
import com.chuantou.yuba.api.to.TrendsImageTO;
import com.chuantou.yuba.api.to.TrendsTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.dao.CacheDao;
import com.chuantou.yuba.pojo.Cache;
import com.chuantou.yuba.ui.widget.OtherProfilePopup;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.ChatUtils;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.LoadCacheTask;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.Utils;
import com.easemob.applib.utils.SmileUtils;
import com.easemob.chat.EMChatManager;

/**
 * 他人资料界面
 * 
 * @author Administrator
 * 
 */
public class OthersProfileActivity extends BaseActionBarActivity implements OnClickListener {
	private Drawable mActionBarBackgroundDrawable;
	private static final String TRENDS_LIST_CACHEKEY_PREFIX = "profile_trends_cache";
	private NetworkImageView mCoverView;
	private NetworkImageView mAvatarView;
	private ImageView mFollowView;
	private TextView mNickNameView;
	private TextView mSignView;
	private TextView mUidView;
	private TextView mTrendsContentView;
	private TextView mSexView;
	private TextView mAgeView;
	private TextView mDistrictView;
	private TextView mFishingAgeView;
	private TextView mFishingPlaceView;
	private NetworkImageView[] mTrendsImages;
	private View mTrendsImageLayout;
	private long mUid;
	private int mScreenWidth;
	private OtherProfilePopup mPopup;
	private OtherUserTO mUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.others_profile);
		mUid = getIntent().getLongExtra(Constants.EXTRA_UID, -1);
		if (mUid <= 0) {
			finish();
			return;
		}
		mActionBarBackgroundDrawable = getResources().getDrawable(R.drawable.bg_actionbar);
		if (!Utils.hasJellyBeanMR1()) {
			mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
			getSupportActionBar().setBackgroundDrawable(mActionBarBackgroundDrawable);
		}
		setActionBarAlpha(0);
		setupViews();
		requestProfile();
		new LoadTrendsCacheTask(getApplicationContext(), getCacheKey(mUid), TrendsDataTO.class).execute();
	}

	private void setupViews() {
		mAvatarView = (NetworkImageView) findViewById(R.id.avatar);
		FrameLayout.LayoutParams avatarLayoutParams = (LayoutParams) mAvatarView.getLayoutParams();
		avatarLayoutParams.bottomMargin = getResources().getDrawable(R.drawable.follow_btn_normal).getIntrinsicHeight() / 2;
		Drawable defaultAvatar = getResources().getDrawable(R.drawable.default_avatar_profile);
		avatarLayoutParams.width = defaultAvatar.getIntrinsicWidth();
		avatarLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;
		avatarLayoutParams.height = defaultAvatar.getIntrinsicHeight();
		mAvatarView.setLayoutParams(avatarLayoutParams);
		mCoverView = (NetworkImageView) findViewById(R.id.cover);
		RelativeLayout.LayoutParams blurLayoutParams = (android.widget.RelativeLayout.LayoutParams) mCoverView.getLayoutParams();
		blurLayoutParams.bottomMargin = getResources().getDrawable(R.drawable.profile_send_message_bg_normal).getIntrinsicHeight() / 2;
		mCoverView.setLayoutParams(blurLayoutParams);
		mFollowView = (ImageView) findViewById(R.id.follow);
		mFollowView.setOnClickListener(this);
		mNickNameView = (TextView) findViewById(R.id.nickname);
		mSignView = (TextView) findViewById(R.id.sign);
		mUidView = (TextView) findViewById(R.id.uid);
		mTrendsContentView = (TextView) findViewById(R.id.trends_content);
		mSexView = (TextView) findViewById(R.id.sex);
		mAgeView = (TextView) findViewById(R.id.age);
		mDistrictView = (TextView) findViewById(R.id.district);
		mFishingAgeView = (TextView) findViewById(R.id.fishing_age);
		mFishingPlaceView = (TextView) findViewById(R.id.fishing_place);
		mTrendsImages = new NetworkImageView[3];
		mTrendsImages[0] = (NetworkImageView) findViewById(R.id.trends_image_1);
		mTrendsImages[1] = (NetworkImageView) findViewById(R.id.trends_image_2);
		mTrendsImages[2] = (NetworkImageView) findViewById(R.id.trends_image_3);
		mTrendsImageLayout = findViewById(R.id.trends_image_layout);
		findViewById(R.id.trends_layout).setOnClickListener(this);
		findViewById(R.id.send_message).setOnClickListener(this);
		mScreenWidth = UiUtil.getScreenWidth(getApplicationContext());
	}

	public void setActionBarAlpha(int alpha) {
		mActionBarBackgroundDrawable.setAlpha(alpha);
		getSupportActionBar().setBackgroundDrawable(mActionBarBackgroundDrawable);
	}

	private Drawable.Callback mDrawableCallback = new Drawable.Callback() {
		@Override
		public void invalidateDrawable(Drawable who) {
			getSupportActionBar().setBackgroundDrawable(who);
		}

		@Override
		public void scheduleDrawable(Drawable who, Runnable what, long when) {

		}

		@Override
		public void unscheduleDrawable(Drawable who, Runnable what) {

		}
	};

	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		getMenuInflater().inflate(R.menu.menu_more, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_more:
			if (UiUtil.isFastDoubleClick() || mUser == null) {
				return true;
			}
			if (mPopup != null && mPopup.isShowing())
				return true;
			mPopup = new OtherProfilePopup(this, mUser);
			ViewGroup decor = (ViewGroup) getWindow().getDecorView();
			mPopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setTrendsData(TrendsDataTO data) {
		TrendsTO trends = (data != null && data.getTrends() != null && !data.getTrends().getTrendsList().isEmpty()) ? data.getTrends().getTrendsList().get(0)
				: null;
		if (trends == null) {
			mTrendsImageLayout.setVisibility(View.GONE);
		} else {
			String content = trends.getContent();
			if (TextUtils.isEmpty(content)) {
				mTrendsContentView.setText(null);
			} else {
				mTrendsContentView.setText(SmileUtils.getSmiledText(getApplicationContext(), content));
			}
			List<TrendsImageTO> images = trends.getImages();
			if (images != null && !images.isEmpty()) {
				mTrendsImageLayout.setVisibility(View.VISIBLE);
				for (int i = 0; i < 3; i++) {
					TrendsImageTO imageTO = i >= images.size() ? null : images.get(i);
					if (imageTO == null) {
						mTrendsImages[i].setVisibility(View.GONE);
					} else {
						mTrendsImages[i].setVisibility(View.VISIBLE);
						BitmapBinder.bindNetImage(getApplicationContext(), mTrendsImages[i], imageTO.getImage(), R.drawable.default_image_small, false);
					}
				}
			} else {
				mTrendsImageLayout.setVisibility(View.GONE);
			}
		}
	}

	private String getCacheKey(long uid) {
		return TRENDS_LIST_CACHEKEY_PREFIX.concat(String.valueOf(uid));
	}

	private void requestProfile() {
		String url = UriHelper.getUserProfileUrl();
		UserTO user = AccountManager.getInstance(getApplicationContext()).getUserTO();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		params.put(UriHelper.PARAMS_PROF_UID, String.valueOf(mUid));
		GsonRequest<OtherUserDataTO> request = new GsonRequest<OtherUserDataTO>(Method.POST, url, new Listener<OtherUserDataTO>() {

			@Override
			public void onResponse(OtherUserDataTO response) {
				if (hasDestroyed())
					return;
				if (response != null && response.isSuccess()) {
					mUser = response.getUser();
					if (mUser != null) {
						mNickNameView.setText(mUser.getUsername());
						mSignView.setText(mUser.getMood());
						mUidView.setText(String.valueOf(mUid));
						mFishingAgeView.setText(String.valueOf(mUser.getFishAge()));
						mFishingPlaceView.setText(mUser.getFishingAddress());
						mDistrictView.setText(mUser.getStateName() + " " + mUser.getCityName());
						Date date = DateUtil.getDateObj(mUser.getBirthday(), DateUtil.PATTERN_YMD);
						int age = (int) ((System.currentTimeMillis() - date.getTime()) / (365L * 24 * 60 * 60 * 1000));
						mAgeView.setText(String.valueOf(age));
						if (Constants.SEX_FEMALE == mUser.getSex()) {
							mSexView.setText(R.string.female);
						} else {
							mSexView.setText(R.string.male);
						}
						mFollowView.setVisibility(mUser.isFollowed() ? View.INVISIBLE : View.VISIBLE);
						String avatarUrl = mUser.getAvatar();
						String coverUrl = mUser.getCover();
						BitmapBinder.bindNetImage(getApplicationContext(), mCoverView, coverUrl, R.drawable.default_cover, false);
						BitmapBinder.bindCircularNetImage(getApplicationContext(), mAvatarView, avatarUrl, R.drawable.default_avatar_round_small);
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		}, params, OtherUserDataTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	class LoadTrendsCacheTask extends LoadCacheTask<TrendsDataTO> {

		public LoadTrendsCacheTask(Context context, String cacheKey, Class<TrendsDataTO> clazz) {
			super(context, cacheKey, clazz);
		}

		@Override
		protected void onPostExecute(Cache<TrendsDataTO> result) {
			super.onPostExecute(result);
			setTrendsData(result == null ? null : result.getData());
			requestTrends();
		}

	}

	/**
	 * 请求最新动态
	 */
	private void requestTrends() {
		final UserTO user = AccountManager.getInstance(getApplicationContext()).getUserTO();
		if (user == null)
			return;
		// 只请求最新的动态
		GsonRequest<TrendsDataTO> request = RequestManager.getTrendsListRequest(new Listener<TrendsDataTO>() {

			@Override
			public void onResponse(TrendsDataTO response) {
				// 开始绑定数据
				if (!hasDestroyed()) {
					setTrendsData(response);
					if (response != null) {
						CacheDao.addOrUpdateCache(getApplicationContext(), getCacheKey(user.getUid()), response);
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					mTrendsImageLayout.setVisibility(View.GONE);
				}
			}
		}, user.getToken(), user.getUid(), mUid, 1, 1);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	public void onFollowClick() {
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				String url = mUser.isFollowed() ? UriHelper.getRemoveFollowUrl() : UriHelper.getAddFollowUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_MATCH_ID, String.valueOf(mUid));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (!hasDestroyed()) {
							if (response != null) {
								if (response.isSuccess()) {
									sendBroadcast(new Intent(Constants.INTENT_ACITON_FRIEND_CHANGED));
									mUser.setFollowed(!mUser.isFollowed());
									Toast.makeText(getApplicationContext(), R.string.operate_success, Toast.LENGTH_SHORT).show();
									mFollowView.setVisibility(mUser.isFollowed() ? View.INVISIBLE : View.VISIBLE);
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(getApplicationContext(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(OthersProfileActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.operate_failed) : msg;
										Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(getApplicationContext(), R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(getApplicationContext(), request);
			}
		}

	}

	public void onBlackListClick() {
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(this, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				String url = mUser.isBlocked() ? UriHelper.getRemoveBlackListUrl() : UriHelper.getAddBlackListUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_MATCH_ID, String.valueOf(mUid));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						String hxuid = ChatUtils.getHXAccount(mUid);
						EMChatManager.getInstance().deleteConversation(hxuid);
						if (!hasDestroyed()) {
							if (response != null) {
								if (response.isSuccess()) {
									ChatActivity activity = ChatActivity.activityInstance;
									if (activity != null && hxuid.equals(activity.getToChatUid())) {
										activity.finish();
									}
									mUser.setBlocked(!mUser.isBlocked());
									Toast.makeText(getApplicationContext(), R.string.operate_success, Toast.LENGTH_SHORT).show();
									new Thread(new Runnable() {
										public void run() {
											ChatUtils.sysBlackList();
										}
									}).start();
									sendBroadcast(new Intent(Constants.INTENT_ACITON_BLACK_LIST_CHANGED));
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(getApplicationContext(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(OthersProfileActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.operate_failed) : msg;
										Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(getApplicationContext(), R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							Toast.makeText(getApplicationContext(), R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(getApplicationContext(), request);
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (UiUtil.isFastDoubleClick())
			return;
		switch (v.getId()) {
		case R.id.follow:
			onFollowClick();
			break;
		case R.id.trends_layout:
			TrendsListActivity.start(this, getString(R.string.others_trends), mUid);
			break;
		case R.id.send_message:
			if (mUser == null)
				return;
			if (mUser.isBlocked()) {
				Toast.makeText(getApplicationContext(), R.string.chat_in_your_blacklist, Toast.LENGTH_SHORT).show();
				return;
			}
			if (mUser.isBlockedBy()) {
				Toast.makeText(getApplicationContext(), R.string.chat_in_his_blacklist, Toast.LENGTH_SHORT).show();
				return;
			}
			ActivityHelper.toChatActivity(this, mUid, mUser.getUsername(), mUser.getAvatar());
			break;
		default:
			break;
		}
	}
}
